from django.db import models
from pygments import highlight
from pygments.formatters.html import HtmlFormatter
from pygments.lexers import get_all_lexers, get_lexer_by_name
from pygments.styles import get_all_styles

# get_all_lexers() 在所有已注册的此词法分析器上返回一个迭代器，
# 返回(longname, tuple of aliases, tuple of filename patterns, tuple of mimetypes) 格式的元组
LEXERS = [item for item in get_all_lexers() if item[1]]
LANGUAGE_CHOICES = sorted([(item[1][0], item[0]) for item in LEXERS])
STYLE_CHOICES = sorted((item, item) for item in get_all_styles())

class Snippet(models.Model):
    # 如果没有models.AutoField,默认会创建一个id的自增列
    created = models.DateTimeField(auto_now_add=True) # auto_now_add 表示当对象第一次被创建时自动设置当前时间，用于创建的时间戳
    title = models.CharField(max_length=100, blank=True, default='')
    code = models.TextField() # 代码
    linenos = models.BooleanField(default=False)
    language = models.CharField(
        choices=LANGUAGE_CHOICES, default='python', max_length=100)
    style = models.CharField(
        choices=STYLE_CHOICES, default='friendly', max_length=100)

    class Meta:
        ordering = ('created',)

    def save(self, *args, **kwargs):
        """
        使用PyGuess库创建突出显示的HTML代码片段的表示
        """
        lexer = get_lexer_by_name(self.language)
        linenos = self.linenos and 'table' or False
        options = self.title and {'title': self.title} or {}
        formatter = HtmlFormatter(
            style=self.style, linenos=linenos, full=True, **options) # 格式化程序
        self.hightlighted = highlight(self.code, lexer, formatter)
        super().save(*args, **kwargs)